package com.gyms.activity;

import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.classic.okhttp.Cons;
import com.classic.okhttp.beans.HVClickInfoBean;
import com.classic.okhttp.beans.HVShareActivityBean;
import com.classic.okhttp.beans.HVVersionBean;
import com.classic.okhttp.enums.Enum;
import com.classic.okhttp.services.ICommonService;
import com.classic.okhttp.services.IUserService;
import com.classic.okhttp.zmoumall.http.ObjectCallback;
import com.classic.okhttp.zmoumall.utils.ToastUtil;
import com.gyms.FragmentController;
import com.gyms.R;
import com.gyms.base.MyAutoLayoutActivity;
import com.gyms.bean.LocationBean;
import com.gyms.constant.Constants;
import com.gyms.manager.BannerIntentManger;
import com.gyms.manager.CommonDialogUtils;
import com.gyms.manager.DataCenter;
import com.gyms.manager.LocationManger;
import com.gyms.manager.StatisticsManager;
import com.gyms.service.StepService;
import com.gyms.view.bottomtablayout.BottomTabLayout;
import com.gyms.view.bottomtablayout.CustomTabEntity;
import com.gyms.view.bottomtablayout.OnTabSelectListener;
import com.gyms.view.bottomtablayout.TabEntity;
import com.orhanobut.logger.Logger;
import com.umeng.socialize.UMShareAPI;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import constant.EventConstant;
import utils.StringUtils;
import weight.ComDialog;
import weight.UiEvent;

public class MainActivity extends MyAutoLayoutActivity implements Handler.Callback{
    @BindView(R.id.fl_context)
    FrameLayout mFlContext;//fragment依赖的布局
    /*@BindView(R.id.rb_home)
    RadioButton mRbHome;//首页按钮
    *//*@BindView(R.id.rb_home1)
    RadioButton mRbHome1;//推荐按钮*//*
    @BindView(R.id.rb_search)
    RadioButton mRbSearch;//搜索按钮
    @BindView(R.id.rb_my)
    RadioButton mRbMy;//我的按钮*/
    @BindView(R.id.tab_layout)
    BottomTabLayout tabLayout;

    //模块名
    private String[] mTitles = {"场馆", "课程", "我的"};
    // 用于tab点击量统计
    private String[] statisticLabel = {"Venue", "Course", "Mine"};
    //模块选中图片
    private int[] mIconSelectIds = {R.mipmap.icon_venue_press, R.mipmap.icon_class_press, R.mipmap.icon_mine_perss};
    //模块未选中图片
    private int[] mIconUnSelectIds = {R.mipmap.icon_venue_normal, R.mipmap.icon_class_normal, R.mipmap.icon_mine_normal};
    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();

    private FragmentController fragmentController;//fragment控制器
    private static Boolean isExit = false;//双击退出标识

    boolean outSideCancel=true;
    boolean isCancelGone=false;

    private LocationManger mLocationManger;

    public Uri mUri;
    private BannerIntentManger bannerIntentManger;//banner 的点击事件

    //动态更换icon相关

    private ComponentName mCNDefault;
    private ComponentName mCNDouble11;
    private ComponentName mCNSongGod;
    private ComponentName mCNZhangHuiMei;
    private ComponentName mCNDengZiQi;
    private PackageManager mPm;
    //自定义icon路径
    private static final String S_Default_PATH="com.gyms.activity.WelcomActivity";//默认启动的路径
    private static final String S_DOUBLE_11_PATH="com.gyms.doubleOne";//双十一icon包路径
    private static final String S_ZHANGXUEYOU_PATH="com.gyms.zhangxueyou";//张学友icon包路径
    private static final String S_ZHANGHUIMEI_PATH="com.gyms.zhanghuimei";//张惠妹icon包路径
    private static final String S_DENGZIQI_PATH="com.gyms.dengziqi";//邓紫棋icon包路径

    private static final String S_DOUBLE_11_FLAG="hlcg_icon_shuang11"; //标识双十一icon
    private static final String S_SONG_GOD_FLAG="hlcg_icon_zhangxueyou";//标识张学友icon
    private static final String S_ZHANG_HUI_MEI_FLAG="hlcg_icon_zhanghuimei";//标识张惠妹icon
    private static final String S_DENG_ZI_QI_FLAG="hlcg_icon_dengziqi";//标识邓紫棋icon
    private String mIcon;
    //动态更换icon相关

    //分享活动相关
    private DataCenter mDataCenter;

    //计步相关
    private long TIME_INTERVAL = 500;//循环取当前时刻的步数中间的间隔时间
    private Messenger messenger;
    private Handler delayHandler;




    ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            try {
                messenger = new Messenger(service);
                Message msg = Message.obtain(null, Constants.MSG_FROM_CLIENT);
                msg.replyTo = mGetReplyMessenger;
                messenger.send(msg);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    protected void setListener() {
        startServiceForStrategy();
    }
    private Messenger mGetReplyMessenger = new Messenger(new Handler(this));

    @Override
    protected void initView() {
        doInitChangIcon();
        mDataCenter=DataCenter.getInstance();
        mLocationManger=LocationManger.getInstance(MainActivity.this);
        EventBus.getDefault().register(this);
        createLoadingView(getString(R.string.str_loading), true);
        getUri();
        fragmentController = FragmentController.getInstance(this, R.id.fl_context);
        fragmentController.showFragment(0);//首次加载首页
        tabLayout.setCurrentTab(0);
        Intent mIntent= getIntent();
        doPushJump(mIntent);
    }


    /**
     * 动态更换icon 初始化
     */

    private void doInitChangIcon() {
        mCNDefault = new ComponentName(
                getBaseContext(),
                S_Default_PATH);
        mCNDouble11 = new ComponentName(
                getBaseContext(),
                S_DOUBLE_11_PATH);
        mCNSongGod = new ComponentName(
                getBaseContext(),
                S_ZHANGXUEYOU_PATH);

        mCNZhangHuiMei = new ComponentName(
                getBaseContext(),
                S_ZHANGHUIMEI_PATH);

        mCNDengZiQi = new ComponentName(
                getBaseContext(),
                S_DENGZIQI_PATH);
        mPm = getApplicationContext().getPackageManager();
    }

    private void doPushJump(Intent mIntent) {
        if(null==mIntent){
            return;
        }
        Bundle mBundle=mIntent.getExtras();
        if(null==mBundle){
            return;
        }
        HVClickInfoBean mClickInfo = (HVClickInfoBean) mBundle.getSerializable(Constants.S_KEY_CLICKINFOBEAN);
        if(null==mClickInfo){
            return;
        }
        doJump(mClickInfo);
    }

    private void doJump(HVClickInfoBean mClickInfo) {
        if(null==bannerIntentManger){
            bannerIntentManger=new BannerIntentManger(this);
        }
            String[] gymIds = mClickInfo.getUrl().split(";");
            if(gymIds.length>0) {
                bannerIntentManger.bannerIntent(mClickInfo,mClickInfo.getAction(),mClickInfo.getTitle(), gymIds);
            }
    }

    private void getUri() {
        mUri=getIntent().getParcelableExtra("key_uri");
    }

    @Override
    protected void processLogic() {
        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new TabEntity(mTitles[i], mIconSelectIds[i], mIconUnSelectIds[i]));
        }

        tabLayout.setTabData(mTabEntities);
        tabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(View mView,int position) {
                fragmentController.showFragment(position);
                //展示动画
                doAnimation(mView);

                StatisticsManager.onEvent(mContext, StatisticsManager.HomePage_Button, statisticLabel[position]);
            }

            @Override
            public void onTabReselect(int position) {

            }
        });

        initUpdate();
    }

    /**
     * 执行动画
     * @param mView mView
     */
    private void doAnimation(View mView) {
        PropertyValuesHolder holder1 = PropertyValuesHolder.ofFloat("scaleX", 1.3f,1f,1.2f,1f,1.1f,1f);
        PropertyValuesHolder holder2 = PropertyValuesHolder.ofFloat("scaleY", 1.3f,1f,1.2f,1f,1.1f,1f);
        ObjectAnimator animator = ObjectAnimator.ofPropertyValuesHolder(mView, holder1, holder2);
        animator.setInterpolator(new LinearInterpolator());
        animator.setDuration(600);
        animator.start();
    }

    /**
     * 检查版本升级
     */
    private void initUpdate() {
        String version = getVersionName();
        final String channel = getChannelName(mContext);
        ICommonService.checkVersion(this, version, channel, Enum.EnumPlatform.Android, false,false, new ObjectCallback<HVVersionBean>() {
            @Override
            public void onSuccess(final HVVersionBean response, String message) {
                if(StringUtils.isNull(response)){
                   return;
                }
                //分享活动相关
                HVShareActivityBean mHVShareActivityBean=response.getShareActivity();
                mDataCenter.setHVShareActivityBean(mHVShareActivityBean);

                //动态更换icon相关
                mIcon=response.icon;
                if(response.getAction()==Enum.EnumVersion.None||response.getAction()==Enum.EnumVersion.Newest){
                    return;
                }
                switch (response.getAction()) {
                    case Force:// 强制升级
                        outSideCancel=false;
                        isCancelGone=true;
                        break;
                    case Prompt://提示升级
                        break;
                }
                final  ComDialog updateDialog= CommonDialogUtils.dialog(MainActivity.this,getSupportFragmentManager(),getString(R.string.str_update),"为了更好的体验,请更新至最新版本","确定", "取消");
               if(isCancelGone){
                   updateDialog.setCancelGone();
               }
                updateDialog.setSubmit(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Uri uri;
                        if(StringUtils.isHttpPic(response.getUrl())){
                            uri = Uri.parse(response.getUrl());
                        }else {
                            uri = Uri.parse(Cons.URL_DOWNLOAD);
                        }
                        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                        startActivity(intent,false);
                       /* if(outSideCancel){
                            updateDialog.dismiss();
                        }*/
                    }
                });
            }

            @Override
            public void onErrorT(int code, HVVersionBean response, String errorMessage) {
                ToastUtil.showToast(mContext, errorMessage);
            }

            @Override
            public void onHttpErrorCall(int statusCode) {

            }
        });
    }

    /**
     *  动态更换icon
     * @param mIcon  hlcg_icon_zhangxueyou 张学友icon  hlcg_icon_shuang11 双十一  空的就是默认icon
     */

    private void doChangeIcon(String mIcon) {
        if(StringUtils.isNull(mIcon)){//默认
            changeIconDefaultIcon();
        }else if(mIcon.equals(S_DOUBLE_11_FLAG)){//双十一
            changeIcon11Icon();
        }else if(mIcon.equals(S_SONG_GOD_FLAG)){
            changeSongGodIcon();
        }else if(mIcon.equals(S_ZHANG_HUI_MEI_FLAG)){
            changeZhangHuiMeiIcon();
        }else if(mIcon.equals(S_DENG_ZI_QI_FLAG)){
            changeDengZiQiIcon();
        }
    }

    /**
     * 获得渠道号
     *
     * @param context
     * @return
     */
    public static String getChannelName(Context context) {
        if (null == context)
            return "呼啦场馆";
        ApplicationInfo appInfo = null;
        try {
            appInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return appInfo.metaData.getString("TD_CHANNEL_ID");
    }

    /**
     * 获得版本号
     *
     * @return
     */
    public String getVersionName() {
        String versionName = "";
        int versioncode = 0;
        try {
            // ---get the package info---
            PackageManager pm = mContext.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(mContext.getPackageName(), 0);
            versionName = pi.versionName;
            versioncode = pi.versionCode;
            if (versionName == null || versionName.length() <= 0) {
                return "";
            }
        } catch (Exception e) {
        }
        return versionName;
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_main;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        FragmentController.onDestroy();
        EventBus.getDefault().unregister(this);
        UMShareAPI.get(this).release();
        unbindService(conn);
        doChangeIcon(mIcon);//应用关闭的时候更新icon
        //解决handler造成的内存泄漏
        delayHandler.removeCallbacksAndMessages(null);

    }

    /**
     * 菜单、返回键响应
     */

    @Override

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exitBy2Click();      //退出应用的操作
        }
        return false;

    }

    /**
     * 双击退出函数
     */

    private void exitBy2Click() {
        if (!isExit) {
            isExit = true; // 准备退出
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            Timer tExit = new Timer();
            tExit.schedule(new TimerTask() {

                @Override

                public void run() {
                    isExit = false; // 取消退出
                }

            }, 2000); // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务
        } else {
            finish();
        }
    }

    //防止fragment重叠
    @Override
    public void onSaveInstanceState(Bundle outState) {
        //super.onSaveInstanceState(outState);将这一行注释掉，阻止activity保存fragment的状态
    }

    @Override
    protected void onResume() {
        super.onResume();
        checkIsChangeCity();
    }

    /**
     * 检查是否需要切换城市
     */

    private void checkIsChangeCity() {
        LocationBean locationBean = DataCenter.getInstance().getLocationBean();
        if (StringUtils.isNull(locationBean)) {

        }
    }

    @Override
    protected boolean supportSlideBack() {
        return false;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @Subscribe
    public void registPush(UiEvent mUiEvent) {
        if (mUiEvent.getKey().equals(EventConstant.FLAG_DO_REGIST_PUSH)) {//注册推送
//            String clientid = (String) mUiEvent.getObject();
            registerNotification();
        }else if(mUiEvent.getKey().equals(EventConstant.FLAG_DO_LOAD_CITY_PUSH)){// 根据地理位置推送
            uploadCityCode();
        }


    }

    /**
     * 	上传地理位置和区号
     */

    private void uploadCityCode() {
        ICommonService.uploadCityCode(this, mLocationManger.getAdCode(), Cons.mDeviceId, Cons.mClientid,mLocationManger.getDetaiAddress(),  2, false, new ObjectCallback<Object>() {
            @Override
            public void onSuccess(Object response, String message) {

            }

            @Override
            public void onErrorT(int code, Object response, String errorMessage) {

            }

            @Override
            public void onHttpErrorCall(int statusCode) {

            }
        });
    }

    /**
     * 注册个推推送
     *
     */

    private void registerNotification() {
        IUserService.registerNotification(this, Cons.mClientid, false, false, new ObjectCallback<Object>() {
            @Override
            public void onSuccess(Object response, String message) {
                Logger.e("Push--->" + message);
            }

            @Override
            public void onErrorT(int code, Object response, String errorMessage) {

            }

            @Override
            public void onHttpErrorCall(int statusCode) {

            }
        });
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case Constants.MSG_FROM_SERVER:
                // 更新界面上的步数
                 Cons.mStep=msg.getData().getInt(Constants.KEY_STEP);
                delayHandler.sendEmptyMessageDelayed(Constants.REQUEST_SERVER, TIME_INTERVAL);
                break;
            case Constants.REQUEST_SERVER:
                try {
                    Message msg1 = Message.obtain(null, Constants.MSG_FROM_CLIENT);
                    msg1.replyTo = mGetReplyMessenger;
                    messenger.send(msg1);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }

                break;
        }
        return false;
    }

    private void startServiceForStrategy() {
        delayHandler = new Handler(this);
        if (!isServiceWork(this, StepService.class.getName())) {
            setupService(true);
        } else {
            setupService(false);
        }
    }

    /**
     * 判断某个服务是否正在运行的方法
     *
     * @param mContext
     * @param serviceName 是包名+服务的类名（例如：net.loonggg.testbackstage.TestService）
     * @return true代表正在运行，false代表服务没有正在运行
     */
    public boolean isServiceWork(Context mContext, String serviceName) {
        boolean isWork = false;
        ActivityManager myAM = (ActivityManager) mContext
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> myList = myAM.getRunningServices(40);
        if (myList.size() <= 0) {
            return false;
        }
        for (int i = 0; i < myList.size(); i++) {
            String mName = myList.get(i).service.getClassName().toString();
            if (mName.equals(serviceName)) {
                isWork = true;
                break;
            }
        }
        return isWork;
    }

    /**
     * 启动service
     *
     * @param flag true-bind和start两种方式一起执行 false-只执行bind方式
     */
    private void setupService(boolean flag) {
        Intent intent = new Intent(this, StepService.class);
        bindService(intent, conn, Context.BIND_AUTO_CREATE);
        if (flag) {
            startService(intent);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        doPushJump(intent);
        mUri=intent.getParcelableExtra("key_uri");
        if(mUri!=null){
            doUriJump(mUri);
        }
    }

    /**
     * 网页唤起app
     * @param mUri uri
     */

    private void doUriJump(Uri mUri) {
        String path = mUri.getPath();
        String mDetailId=path.split("/")[2];
        String mDetailType=path.split("/")[1];
        if(mDetailType.equals("venue")){//跳转场馆详情
            goGymDetail(mDetailId);
        }else{
            goProductDetail(mDetailId);
        }
    }

    private void goGymDetail(String venueId) {
        Bundle mBundle = new Bundle();
        mBundle.putString(Constants.FLAG_INTENT_VENUEID, venueId);
        startActivity(GymDetailActivity.class, mBundle, false);
    }

    private void goProductDetail(String mProductId) {
        Intent intent = new Intent(mContext, ProductDetailsActivity.class);
        intent.putExtra("productId", mProductId);
        startActivity(intent, false);
    }

    /**
     * 开启服务
     * @param componentName componentName
     */

    private void enableComponent(ComponentName componentName) {
        mPm.setComponentEnabledSetting(componentName,
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);
    }

    /**
     * 禁止服务
     * @param componentName componentName
     */

    private void disableComponent(ComponentName componentName) {
        mPm.setComponentEnabledSetting(componentName,
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP);
    }

    /**
     * 启用双十一icon
     */

    public void changeIcon11Icon() {
        disableComponent(mCNDefault);
        disableComponent(mCNSongGod);
        disableComponent(mCNDengZiQi);
        disableComponent(mCNZhangHuiMei);
        enableComponent(mCNDouble11);
    }

    /**
     * 启用默认icon
     */

    public void changeIconDefaultIcon(){
        disableComponent(mCNDouble11);
        disableComponent(mCNSongGod);
        disableComponent(mCNZhangHuiMei);
        disableComponent(mCNDengZiQi);
        enableComponent(mCNDefault);
    }

    /**
     * 启用张学友抢票icon
     */

    public void changeSongGodIcon(){
        disableComponent(mCNDouble11);
        disableComponent(mCNZhangHuiMei);
        disableComponent(mCNDengZiQi);
        disableComponent(mCNDefault);
        enableComponent(mCNSongGod);
    }

    /**
     * 启用张惠妹icon
     */

    public void changeZhangHuiMeiIcon(){
        disableComponent(mCNDouble11);
        disableComponent(mCNSongGod);
        disableComponent(mCNDengZiQi);
        disableComponent(mCNDefault);
        enableComponent(mCNZhangHuiMei);
    }

    /**
     * 启用邓紫棋
     */

    public void changeDengZiQiIcon(){
        disableComponent(mCNDouble11);
        disableComponent(mCNSongGod);
        disableComponent(mCNZhangHuiMei);
        disableComponent(mCNDefault);
        enableComponent(mCNDengZiQi);
    }


}
